import './style.css';
import * as THREE from 'three';
import PhysicsWorld from './World.js';
import Car from './Car.js';
import CameraController from './Camera.js';

console.log('Script Start - Vite');

// 创建场景
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x333333, 30, 80);

// 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(10, 8, 15);
camera.lookAt(0, 1, 0);

// 获取画布
const canvas = document.getElementById('c');
if (!canvas) {
    throw new Error("Canvas element with id 'c' not found!");
}

// 创建渲染器
const renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setClearColor(0x333333);

// 添加灯光
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);

const directionalLight = new THREE.DirectionalLight(0xffffff, 0.7);
directionalLight.position.set(25, 35, 20);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
directionalLight.shadow.camera.near = 1;
directionalLight.shadow.camera.far = 80;
directionalLight.shadow.camera.left = -40;
directionalLight.shadow.camera.right = 40;
directionalLight.shadow.camera.top = 40;
directionalLight.shadow.camera.bottom = -40;
scene.add(directionalLight);

// 初始化物理世界
const physicsWorld = new PhysicsWorld(scene);
const world = physicsWorld.getWorld();

// 创建车辆
const car = new Car(world, scene);

// 创建车辆实例后，设置相机
car.setCamera(camera);

// 创建相机控制器
const cameraController = new CameraController(camera, renderer);

// 窗口大小调整事件
window.addEventListener('resize', () => {
    renderer.setSize(window.innerWidth, window.innerHeight);
}, false);

// 动画循环
const clock = new THREE.Clock();
let frameCount = 0;

function animate() {
    requestAnimationFrame(animate);
    
    const dt = clock.getDelta();
    
    // 更新物理世界
    physicsWorld.update(dt);
    
    // 更新车辆
    car.update(dt);
    
    // 注释掉 CameraController 的更新，只使用 Car 类中的相机更新
    // cameraController.update(car.getChassisBody());
    
    // 渲染场景
    renderer.render(scene, camera);
    
    // 帧计数
    frameCount++;
}

// 开始动画
animate();